package com.ztf0337.mycurriculumdesign.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.entity.User;
import com.ztf0337.mycurriculumdesign.service.UserService;

public class RegisterActivity extends AppCompatActivity {

    UserService userService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        userService = new UserService(this);

        TextView tvLogin = findViewById(R.id.tvLogin);
        tvLogin.setOnClickListener(v -> {
            finish();
        });

        Button btnRegister = findViewById(R.id.btnRegister);
        btnRegister.setOnClickListener(v -> {
            EditText etName,etPhone,etPassword,etRPassword;
            TextView tvHint;

            etName = findViewById(R.id.etName);
            etPhone = findViewById(R.id.etPhone);
            etPassword = findViewById(R.id.etPassword);
            etRPassword = findViewById(R.id.etRPassword);

            String name = etName.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            String rPassword = etRPassword.getText().toString().trim();

            tvHint = findViewById(R.id.tvHint);
            if (name.isBlank()) {
                name = "空";
            }
            if (phone.isBlank()) {
                tvHint.setText("手机号为空");
                return;
            }
            if (phone.length() != 11) {
                tvHint.setText("手机号格式错误");
                return;
            }
            if (!password.equals(rPassword)) {
                tvHint.setText("前后两次密码不同");
                return;
            }
            if (password.isBlank()) {
                tvHint.setText("密码为空");
                return;
            }
            if (password.length() < 6) {
                tvHint.setText("密码过短（<6）");
                return;
            }
            User user = new User();
            user.setName(name);
            user.setPhone(phone);
            user.setPassword(password);
            user.setStatus(true);
            user.setRoot(false);

            int register = userService.register(user);

            if (register == 0) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, LoginActivity.class);
                intent.putExtra("phone",phone);
                intent.putExtra("online",true);
                this.startActivity(intent);
            } else {
                tvHint.setText("手机号重复注册");
                return;
            }

        });
    }
}
